package com.inxedu.os.common.controller;

import com.inxedu.os.common.constants.CommonConstants;
import com.inxedu.os.common.util.DateUtils;
import com.inxedu.os.common.util.FileUploadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;

/**
 * @author www.inxedu.com
 *
 */
@Controller
@RequestMapping("/image")
public class ImageUploadController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(ImageUploadController.class);
	private List<String> fileTypeList;

	/**
	 *	获得项目根目录
     */
	private String getProjectRootDirPath(HttpServletRequest request){
		return request.getSession().getServletContext().getRealPath("/");

	}

	/**
	 * 图片上传，原图保存
	 * @param request
	 * @param response
	 * @param uploadfile 文件数据
	 * @param param 参数据
	 * @param fileType 允许上传类型
	 * @param pressText 是否上水印
	 * @return
	 */
	@RequestMapping(value="/gok4",method={RequestMethod.POST})
	public String gok4(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="uploadfile" ,required=true) MultipartFile uploadfile,
			@RequestParam(value="param",required=false) String param,
			@RequestParam(value="fileType",required=true) String fileType,
			@RequestParam(value="pressText",required=false) String pressText){
		try{
			//最大文件大小
			long maxSize = 4096000;
			System.out.println(uploadfile.getSize());
			//检查文件大小
			if(uploadfile

					.getSize() > maxSize){
				return responseErrorData(response,1,"上传的图片大小不能超过4M。");
			}

			String[] type = fileType.split(",");
			//设置图片类型
			setFileTypeList(type);
			//获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
			String ext = FileUploadUtils.getSuffix(uploadfile.getOriginalFilename());
			if(!fileType.contains(ext)||"jsp".equals(ext)){
				return responseErrorData(response,1,"文件格式错误，上传失败。");
			}
			//获取文件路径
			String filePath = getPath(request,ext,param);
			File file = new File(getProjectRootDirPath(request)+filePath);

			//如果目录不存在，则创建
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}
			//保存文件
			uploadfile.transferTo(file);
			//上水印
//			if(pressText!=null && pressText.equals("true")){
//				FileUploadUtils.pressText("inxedu", file.getPath(), file.getPath(), "Segoe Script", Font.BOLD, Color.BLUE,0.2f);
//			}
			//返回数据

			return responseData(filePath,0,"上传成功",response);
		}catch (Exception e) {
			logger.error("gok4()--error",e);
			return responseErrorData(response,2,"系统繁忙，上传失败");
		}
	}
	
	/**
	 * 编辑器图片上传，原图保存
	 * @param request
	 * @param response
	 * @param param 参数据
	 * @param fileType 允许上传类型
	 * @param pressText 是否上水印
	 * @return
	 */
	@RequestMapping(value="/keupload",method={RequestMethod.POST})
	public String kindEditorUpload(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value="param",required=false) String param,
			@RequestParam(value="fileType",required=true) String fileType,
			@RequestParam(value="pressText",required=false) String pressText){
		try{
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
			MultipartFile imgFile = multipartRequest.getFile("imgFile");
			if(imgFile==null){
				return responseData("",1,"请选择上传的文件，上传失败",response);
			}
			//最大文件大小
			long maxSize = 4096000;
			System.out.println(imgFile.getSize());
			//检查文件大小
			if(imgFile.getSize() > maxSize){
				return responseErrorData(response,1,"上传的图片大小不能超过4M。");
			}

			String[] type = fileType.split(",");
			//设置图片类型
			setFileTypeList(type);
			//获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名  
			String ext = FileUploadUtils.getSuffix(imgFile.getOriginalFilename());
			if(!fileType.contains(ext)||"jsp".equals(ext)){
				return responseErrorData(response,1,"文件格式错误，上传失败。");
			}
			//获取文件路径
			String filePath = getPath(request,ext,param);
			File file = new File(getProjectRootDirPath(request)+filePath);

			//如果目录不存在，则创建
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}
			//保存文件
			imgFile.transferTo(file);
			//上水印
//			if(pressText!=null && pressText.equals("true")){
//				FileUploadUtils.pressText("inxedu", file.getPath(), file.getPath(), "Segoe Script", Font.BOLD, Color.BLUE,0.2f);
//			}
			//返回数据
			return responseData(filePath,0,"上传成功",response);
		}catch (Exception e) {
			logger.error("kindEditorUpload()--error",e);
			return responseErrorData(response,2,"系统繁忙，上传失败。");
		}
	}

	/**
	 * 图片上传（带缩列图）
	 * @param request
	 * @param response
	 * @param param 参数据
	 * @param fileType 允许上传类型
	 * @param pressText 是否上水印
	 * @return
	 */
	@RequestMapping(value="/shrinkDiagram",method={RequestMethod.POST})
	@ResponseBody
	public String kindEditorUploadShrinkDiagram(HttpServletRequest request,HttpServletResponse response,
								   @RequestParam(value="param",required=false) String param,
								   @RequestParam(value="fileType",required=true) String fileType,
								   @RequestParam(value="pressText",required=false) String pressText){
		try{
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
			MultipartFile imgFile = multipartRequest.getFile("imgFile");
			if(imgFile==null){
				return responseData("",1,"请选择上传的文件，上传失败",response);
			}
			//最大文件大小
			long maxSize = 1024000;
			System.out.println(imgFile.getSize());
			//检查文件大小
			if(imgFile.getSize() > maxSize){
				return responseErrorData(response,1,"上传文件大小超过限制。");
			}

			String[] type = fileType.split(",");
			//设置图片类型
			setFileTypeList(type);
			//获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
			String ext = FileUploadUtils.getSuffix(imgFile.getOriginalFilename());
			if(!fileType.contains(ext)||"jsp".equals(ext)){
				//return responseData("",1,"文件格式错误，上传失败");
				return responseErrorData(response,1,"文件格式错误，上传失败。");
			}
			//获取文件路径
			String filePath = getPath(request,ext,param);
			File file = new File(getProjectRootDirPath(request)+filePath);

			//如果目录不存在，则创建
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}
			//保存文件
			imgFile.transferTo(file);
			//上水印
//			if(pressText!=null && pressText.equals("true")){
//				FileUploadUtils.pressText("inxedu", file.getPath(), file.getPath(), "Segoe Script", Font.BOLD, Color.BLUE,0.2f);
//			}



			String width = request.getParameter("width");
			String height = request.getParameter("height");
			//返回缩列图
			String smallUrl=zoomImage(request,filePath,Integer.valueOf(width), Integer.valueOf(height));
			//返回数据

			Map<String,Object> map = new HashMap<String, Object>();
			map.put("url", filePath);
			map.put("error", 0);
			map.put("message", "上传成功");
			map.put("smallurl",smallUrl);
			String url = gson.toJson(map);
			/*response.setContentType("text/html;charset=utf-8");
			PrintWriter out=response.getWriter();
			out.println(url);*/
			return url;
		}catch (Exception e) {
			logger.error("kindEditorUpload()--error",e);
			//return responseData("",2,"系统繁忙，上传失败");
			return responseErrorData(response,2,"系统繁忙，上传失败。");
		}
	}


	
	/**
	 * 用户头像上传
	 */
	@RequestMapping({ "/saveface" })
	@ResponseBody
	public String saveface(HttpServletRequest request,HttpServletResponse response) {
		try {
			String photoPath = request.getParameter("photoPath");
			
			//原图片的宽（现显示的宽度，非原图片宽度）
			int imageWidth = Integer.parseInt(request.getParameter("txt_width"));
			//原图片的高（现显示的高度，非原图片高度）
			int imageHeight = Integer.parseInt(request.getParameter("txt_height"));
			
			//因页面显示关系，需要转换图片大小（转成现页面显示的图片大小）
			//FileUploadUtils.changeSize(getProjectRootDirPath(request)+photoPath,getProjectRootDirPath(request)+photoPath,imageWidth,imageHeight);

			//选中区域距离顶部的大小
			int cutTop = Integer.parseInt(request.getParameter("txt_top"));
			//选中区域距离左边的大小
			int cutLeft = Integer.parseInt(request.getParameter("txt_left"));

			//选中区域的宽
			int dropWidth = Integer.parseInt(request.getParameter("txt_DropWidth"));
			//选中区域的高
			int dropHeight = Integer.parseInt(request.getParameter("txt_DropHeight"));
			
			String ext = FileUploadUtils.getSuffix(photoPath);
			if("jsp".equals(ext)){
				return responseErrorData(response,1,"文件格式错误，上传失败。");
			}
			String newPath = getPath(request,ext,"customer");
			FileUploadUtils.cut(getProjectRootDirPath(request)+photoPath, getProjectRootDirPath(request)+newPath, cutLeft, cutTop, dropWidth, dropHeight,imageWidth,imageHeight);
			//上传剪裁完成后，删除模板图片
			File file = new File(getProjectRootDirPath(request)+photoPath);
			if(file.exists()){
				file.delete();
			}

			//最大文件大小
			long maxSize = 4096000;
			System.out.println(file.length());
			//检查文件大小
			if(file.length() > maxSize){
				return responseErrorData(response,1,"上传的图片大小不能超过4M。");
			}

			Map<String,Object> map = new HashMap<String,Object>();
			map.put("src",newPath);
			map.put("status","1");
			return gson.toJson(map);
		} catch (Exception e) {
			logger.error("saveface()---error", e);
		}
		return null;
	}

	/**
	 * swf使用上传文件
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/uploadfile")
	@ResponseBody
	public String uploadfile(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="param",required=false) String param) {
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile imgFile = multipartRequest.getFile("fileupload");
			//获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
			String ext = FileUploadUtils.getSuffix(imgFile.getOriginalFilename());
			if("jsp".equals(ext)){
				return responseErrorData(response,1,"文件格式错误，上传失败。");
			}
			//获取文件路径
			String filePath = getPath(request,ext,param);
			File file = new File(getProjectRootDirPath(request)+filePath);

			//如果目录不存在，则创建
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}
			//保存文件
			imgFile.transferTo(file);

			logger.info("++++upload img return:" + filePath);
			return filePath;
		} catch (Exception e) {
			logger.error("uploadfile error", e);
		}
		return null;
	}
	/**
	 * swf使用上传文件
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/uploadfileToTemplate")
	@ResponseBody
	public String uploadfileToTemplate(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="param",required=false) String param) {
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile imgFile = multipartRequest.getFile("fileupload");
			//获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
			String ext = FileUploadUtils.getSuffix(imgFile.getOriginalFilename());
			if("jsp".equals(ext)){
				return responseErrorData(response,1,"文件格式错误，上传失败。");
			}
			//获取文件路径
			String filePath = getFilePath(request,ext,param);
			File file = new File(getProjectRootDirPath(request)+filePath);

			//如果目录不存在，则创建
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}
			//保存文件
			imgFile.transferTo(file);

			logger.info("++++upload img return:" + filePath);
			return filePath;
		} catch (Exception e) {
			logger.error("uploadfile error", e);
		}
		return null;
	}


	/**
	 * 删除文件
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/deletefile",method= RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> deleteFile(HttpServletRequest request,@RequestParam(value="filePath",required=true) String filePath){
		Map<String,Object> json = new HashMap<String,Object>();
		try{
			if(filePath!=null && filePath.trim().length()>0 && filePath.startsWith("/images/upload/")){
				File file = new File(getProjectRootDirPath(request)+filePath);

				if(file.exists()){
					file.delete();
					json = this.setJson(true, "文件删除成功", null);
				}else{
					json = this.setJson(false, "文件不存在，删除失败", null);
				}
			}else{
				json = this.setJson(false, "删除失败", null);
			}
		}catch (Exception e) {
			json = this.setJson(false, "系统繁忙，文件删除失败", null);
			logger.error("deleteFile()--error",e);
		}
		return json;
	}
	
	//--------------------------------------------------------------------------------------
	
	/**
	 * 获取文件保存的路径
	 * @param request
	 * @param ext 文件后缀
	 * @param param 传入参数
	 * @return 返回文件路径
	 */
	private String getPath(HttpServletRequest request,String ext,String param){
		String filePath = "/images/upload/";
		if(param!=null && param.trim().length()>0){
			filePath+=param;
		}else{
			filePath+= CommonConstants.projectName;
		}
		filePath+="/"+ DateUtils.toString(new Date(), "yyyyMMdd")+"/"+System.currentTimeMillis()+"."+ext;
		return filePath;
	}
	private String getFilePath(HttpServletRequest request,String ext,String param){
		String filePath = "/template/templet1/";
		if(param!=null && param.trim().length()>0){
//			filePath+=param;
			filePath+= CommonConstants.projectName;

		}else{
			filePath+= CommonConstants.projectName;
		}
		filePath+="/"+ DateUtils.toString(new Date(), "yyyyMMdd")+"/"+System.currentTimeMillis()+"."+ext;
		return filePath;
	}
	
	/**
	 * 返回数据
	 * @param path 文件路径
	 * @param error 状态 0成功 其状态均为失败
	 * @param message 提示信息
	 * @return 回调路径 
	 */
	public String responseData(String path,int error,String message,HttpServletResponse response) throws IOException {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("url", path);
		map.put("error", error);
		map.put("message", message);
		response.getWriter().write(gson.toJson(map));
		return null;
	}

	/**
	 * 返回错误数据
	 * @param error 状态 0成功 其状态均为失败
	 * @param message 提示信息
	 */
	public String responseErrorData(HttpServletResponse response,int error,String message){
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("error", error);
			map.put("message", message);
			response.setContentType("application/json; charset=UTF-8");
			response.getWriter().print(gson.toJson(map));
			response.getWriter().flush();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 设置图片类型
	 */
	public void setFileTypeList(String[] type){
		fileTypeList = new ArrayList<String>();
		for(String _t : type){
			fileTypeList.add(_t);
		}
	}



	/**
	 * 由原图图生成指定宽高的jpg小图
	 */
	public String zoomImage(HttpServletRequest request,String srcFileName,int width, int height) {
		String tagFileName = srcFileName.substring(0, srcFileName.lastIndexOf("."))+"-small"+srcFileName.substring(srcFileName.lastIndexOf("."), srcFileName.length());
		srcFileName = getProjectRootDirPath(request) +srcFileName;
		try {

			//得到原图片
			BufferedImage bufferedImage= ImageIO.read(new File(srcFileName));

			//获取图片高宽
			int srcWidth=bufferedImage.getWidth();
			int srcHeight=bufferedImage.getHeight();
			float _scale = Float.valueOf(width)/srcWidth;
			srcHeight = (int)(Float.valueOf(srcHeight)*_scale);

			/** width - 将图像缩放到的宽度。 height - 将图像缩放到的高度。 hints - 指示用于图像重新取样的算法类型的标志。  */
			Image image = bufferedImage.getScaledInstance(width, srcHeight,Image.SCALE_SMOOTH);

			ImageFilter cropFilter = new CropImageFilter(0, 0, width, height);
			Image img = Toolkit.getDefaultToolkit().createImage(
					new FilteredImageSource(image.getSource(),cropFilter));
			BufferedImage outputImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics g = outputImage.getGraphics();
			g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图
			g.dispose();

			//写出新的图片
			ImageIO.write(outputImage, FileUploadUtils.getSuffix(getProjectRootDirPath(request) +tagFileName), new File(getProjectRootDirPath(request) +tagFileName));

		} catch (IOException e) {
			e.printStackTrace();
		}
		return tagFileName;
	}
	
}
